package cn.im.qywx.queue;

import cn.im.qywx.system.SystemParams;
import cn.im.qywx.util.DateUtils;
import cn.im.qywx.view.ImWxToken;
import com.google.gson.Gson;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * token更新管理
 */
@Slf4j
public class TokenQueue {

    public static Map<String,ImWxToken> tokenMap = new HashMap<String, ImWxToken>();

    /**
     *  获取发送消息令牌
     * @return
     */
    public static String getToken(String agentId) {
        ImWxToken wxToken = tokenMap.get(agentId);
        if(wxToken==null){
            return "";
        }else if(wxToken.getValidTime() < System.currentTimeMillis()){
            reFreshToken(wxToken);
        }
        return wxToken.getToken();
    }


    /**
     * 刷新Token
     */
    public static void reFreshToken(ImWxToken wxToken) {
        String tokenJson;
        Gson gson;
        TokenJson tJson;
        RestTemplate restTemplate = new RestTemplate();

        try {
            log.info("wxToken:{}",wxToken.toString());
            // 全局access_token
            tokenJson = restTemplate.getForObject(SystemParams.URL_TOKEN+"&corpsecret=" + wxToken.getSecret(),String.class);
            gson = new Gson();
            tJson = gson.fromJson(tokenJson, TokenJson.class);


            if (null != tJson && !StringUtils.isEmpty(tJson.getAccess_token())) {

                wxToken.setToken(tJson.getAccess_token());
                wxToken.setValidTime(System.currentTimeMillis() + tJson.getExpires_in());

                Date date = new Date(wxToken.getValidTime());

               log.info( "refresh Token. token:"+wxToken.getToken() + " validTime:" + DateUtils.date2String(date, "yyyyMMdd HH:mm:ss") );
            }else{
               log.info("refresh token error. " + tJson);
            }

        } catch (Exception e) {
            e.printStackTrace();//捕获到异常
        }
    }

    class TokenJson {
        private String access_token;
        private int expires_in;
        private String errcode;
        private String errmsg;

        public String getAccess_token() {
            return access_token;
        }

        public void setAccess_token(String access_token) {
            this.access_token = access_token;
        }

        public int getExpires_in() {
            return expires_in;
        }

        public void setExpires_in(int expires_in) {
            this.expires_in = expires_in;
        }

        public String getErrcode() {
            return errcode;
        }

        public void setErrcode(String errcode) {
            this.errcode = errcode;
        }

        public String getErrmsg() {
            return errmsg;
        }

        public void setErrmsg(String errmsg) {
            this.errmsg = errmsg;
        }

    }
}
